class AIAssistant {
  name = "语音助理";
  intervalCommentsId = null; /*定时器id*/
  intervalWelId = null; /*定时器id*/

  running = 0; /*0等在开始 1运行中*/

  voiceMap = {
    Google_SC: "Google 普通话（中国大陆）",
    Kangkang_SC: "Microsoft Kangkang - Chinese (Simplified, PRC)"
  };

  voiceName = "Kangkang_SC";

  constructor({ name, voiceName }) {
    this.name = name || this.name;
    this.voiceName = voiceName || this.voiceName;
  }
  start() {
    this.running = 1;
    this.intervalCommentsId = this.playCommentMessage();
    this.intervalWelId = this.palyWelcome();
  }

  clear() {
    this.running = 0;
    window.clearInterval(this.intervalWelId);
    window.clearInterval(this.intervalCommentsId);
  }

  playCommentMessage() {
    return setInterval(() => {
      const giftElements = document.querySelectorAll(
        ".webcast-chatroom___item.webcast-chatroom___enter-done"
      );
      const currentGiftElement = giftElements[giftElements.length - 1];

      const lastMessage = sessionStorage.getItem("MESSAGE_GIFT");
      let currentMessage = currentGiftElement && currentGiftElement.innerText;

      if (
        !currentMessage ||
        (currentMessage && currentMessage.indexOf("来了") !== -1)
      ) {
        console.error("currentMessage", currentMessage);
        return;
      }

      if (
        currentMessage === lastMessage ||
        currentMessage.includes("欢迎来到直播间！")
      ) {
        /*console.log("重复");*/
        return;
      }
      sessionStorage.setItem("MESSAGE_GIFT", currentMessage);

      currentMessage = currentMessage.replace(/(.+?)\1{2}/g, "$1");

      if (/送出了/gi.test(currentMessage)) {
        let name = currentMessage.slice(0, currentMessage.indexOf("送出了"));

        const match = currentMessage.match(/\d{1,}$/);
        if (match) {
          const number = Number(match[0]);
          currentMessage = `感谢${name}送${number}个礼物`;
        } else {
          currentMessage = `感谢${name}送的礼物`;
        }
      }

      this.sayMessage(currentMessage);

      if (
        /(你是什么|这是|这是啥|这个是啥|这是什么|啥玩意|干什么|干啥|啥意思|api)/.test(
          currentMessage
        )
      ) {
        this.sayMessage("我是你的人工智能助理", "Kangkang_SC");
      }
      if (
        /(这用啥写的|怎么做的|什么语言|识别|代码|源码|如何学习|想要|源代码)/.test(
          currentMessage
        )
      ) {
        this.sayMessage("点关注 亮灯排 送代码", "Kangkang_SC");
      }
      if (/(怎么进群|进群|粉丝群)/.test(currentMessage)) {
        this.sayMessage("点关注 私聊我 进粉丝群", "Kangkang_SC");
      }
      if (/(没有欢迎|不欢迎|没有我|我呢|欢迎|不读|bug)/.test(currentMessage)) {
        const index = currentMessage.indexOf("：");
        if (index !== -1) {
          this.sayMessage(
            currentMessage.slice(0, index) + "欢迎你",
            "Kangkang_SC"
          );
        }
      }
      if (/(夸)/.test(currentMessage)) {
        const index = currentMessage.indexOf("：");
        if (index !== -1) {
          this.sayMessage(
            "夸夸你" + currentMessage.slice(0, index),
            "Kangkang_SC"
          );
        }
      }
      if (/(卧槽|尼玛)/.test(currentMessage)) {
        this.sayMessage("请文明用语", "Kangkang_SC");
      }
      if (/(6|牛|厉害|棒|实力|稀缺|真不错|大哥|六|liu)/.test(currentMessage)) {
        this.sayMessage("谢谢你夸我", "Kangkang_SC");
      }
    }, 800);
  }
  palyWelcome() {
    return setInterval(() => {
      const bottomElements = document.querySelectorAll(
        ".webcast-chatroom___bottom-message"
      );
      const currentElement = bottomElements[bottomElements.length - 1];

      const lastMessage = sessionStorage.getItem("MESSAGE_BOTTOM");
      const currentMessage = currentElement && currentElement.innerText;

      if (currentMessage === lastMessage) {
        console.log("重复");
        return;
      }
      sessionStorage.setItem("MESSAGE_BOTTOM", currentMessage);
      /*console.log("欢迎 ", currentMessage);*/
      let sayText = currentMessage;
      if (sayText.indexOf("来了") !== -1) {
        sayText = currentMessage.replace(/来了$/gi, "");
        sayText = "欢迎 " + sayText;
      }

      this.sayMessage(sayText);
    }, 1500);
  }

  sayMessage(currentMessage = "", voiceName = "Kangkang_SC") {
    /*console.log("sayMessage", currentMessage, voiceName);*/
    console.log(currentMessage);

    const voiceMap = this.voiceMap;

    /*把数据存储在服务端*/
    window
      .fetch(`http://localhost:3300/?data=${currentMessage}`)
      .catch((error) => {
        console.log("window.fetch error", error);
      });

    const say = new window.SpeechSynthesisUtterance(currentMessage || "");

    say.volume = window.volume || 1;
    say.voice = window.speechSynthesis
      .getVoices()
      .filter((voice) => voice.name === voiceMap[voiceName])[0];

    window.speechSynthesis.speak(say);
  }
}

const aIAssistant = new AIAssistant({ name: "直播语音助理" });
aIAssistant.start();

/* 
 1. 存在bug 同时进来有可能有的人不读取
*/

/*https://live.douyin.com/252989917313*/
